<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态
check_login();

// 初始化数据库连接
$db = db_connect();

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $content = trim($_POST['content']);
    $category = trim($_POST['category']);
    $status = isset($_POST['status']) ? 1 : 0;
    $cover_image = ''; // 默认空图片路径

    // 处理文件上传
    if (!empty($_FILES['cover_image']['name'])) {
        $target_dir = "../api/user/uploads/guides/";
        // 确保目录存在
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $imageFileType = strtolower(pathinfo($_FILES["cover_image"]["name"], PATHINFO_EXTENSION));
        $new_filename = date('Ymd_His') . '_' . uniqid() . '.' . $imageFileType;
        $target_file = $target_dir . $new_filename;

        // 检查文件类型
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($imageFileType, $allowed_types)) {
            if (move_uploaded_file($_FILES["cover_image"]["tmp_name"], $target_file)) {
                $cover_image = 'uploads/guides/' . $new_filename;
            } else {
                redirect('fitness_guide_add.php', '文件上传失败，请重试。', 'error');
                exit();
            }
        } else {
            redirect('fitness_guide_add.php', '只允许上传 JPG, JPEG, PNG 和 GIF 文件。', 'error');
            exit();
        }
    }

    try {
        // 插入数据库
        $stmt = $db->prepare("INSERT INTO fitness_guides (title, content, category, cover_image, status, create_time) VALUES (:title, :content, :category, :cover_image, :status, NOW())");
        $stmt->bindValue(':title', $title);
        $stmt->bindValue(':content', $content);
        $stmt->bindValue(':category', $category);
        $stmt->bindValue(':cover_image', $cover_image);
        $stmt->bindValue(':status', $status);
        
        if ($stmt->execute()) {
            redirect('fitness_guides.php', '添加成功');
        } else {
            redirect('fitness_guide_add.php', '添加失败，请重试。', 'error');
        }
    } catch (Exception $e) {
        redirect('fitness_guide_add.php', '系统错误：' . $e->getMessage(), 'error');
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加健身指南 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
    .card {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        padding: 25px;
    }
    .preview-image {
        max-width: 200px;
        max-height: 120px;
        object-fit: cover;
        border-radius: 4px;
        margin-top: 10px;
    }
    .form-group {
        margin-bottom: 20px;
    }
    .form-control {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        transition: border-color 0.3s;
    }
    .form-control:focus {
        border-color: #3498db;
        outline: none;
    }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>添加健身指南</h2>
                </div>
                <div class="header-right">
                    <a href="fitness_guides.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> 返回列表
                    </a>
                </div>
            </header>

            <div class="content">
                <div class="card">
                    <form action="" method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="title">标题</label>
                            <input type="text" id="title" name="title" class="form-control" required>
                        </div>

                        <div class="form-group">
                            <label for="category">分类</label>
                            <select name="category" id="category" class="form-control" required>
                                <option value="入门指导">入门指导</option>
                                <option value="减脂">减脂</option>
                                <option value="增肌">增肌</option>
                                <option value="塑形">塑形</option>
                                <option value="营养">营养</option>
                                <option value="恢复">恢复</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="cover_image">封面图片</label>
                            <input type="file" name="cover_image" id="cover_image" class="form-control" accept="image/*">
                            <div class="image-preview"></div>
                        </div>

                        <div class="form-group">
                            <label for="content">内容</label>
                            <textarea name="content" id="content" rows="10" class="form-control" required></textarea>
                        </div>

                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="status" value="1" checked>
                                启用指南
                            </label>
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
    // 图片预览功能
    document.getElementById('cover_image').onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.querySelector('.image-preview');
                preview.innerHTML = `<img src="${e.target.result}" class="preview-image">`;
            }
            reader.readAsDataURL(file);
        }
    };
    </script>
</body>
</html>
?> 